﻿using ServerBase.LunarSocket;
using System;
using System.Net.Sockets;
using UtilPublic.Serialization;
using WebSocket4Net;

namespace ServerBase.Client
{
    public class LunarClientLink
    {
        private WebSocket websocket = null;

        public string LinkIp = "127.0.0.1";
        public int LinkId = 12201;
        public string LinkPath = "/Lunar";
        public bool LinkState = false;

        //初始化
        public void Setup(string ip, int port, string path = "/Lunar")
        {
            LinkIp = ip;
            LinkId = port;
            LinkPath = path;
        }
        public bool Start()
        {
            try
            {
                websocket = new WebSocket($"ws://{LinkIp}:{LinkId}{LinkPath}");

                websocket.Opened += websocket_Opened;
                websocket.Closed += websocket_Closed;
                websocket.MessageReceived += websocket_MessageReceived;
                websocket.Open();

                LinkState = true;

                return true;
            }
            catch (SocketException ex)
            {
                websocket = null;

                LinkState = false;
                //网络连接异常

                LunarClientDebug.Error($"连接失败 {LinkIp} {LinkId} {ex.Message}！");

                return false;
            }
        }
        private void websocket_MessageReceived(object sender, MessageReceivedEventArgs e)
        {
            //this.listBox1.Invoke(new EventHandler(ShowMessage), e.Message);
            MessageReceivedEventArgs responseMsg = (MessageReceivedEventArgs)e; //接收服务端发来的消息
            string strMsg = responseMsg.Message;

            LunarClientDispatcher.OnReceiveData(new LunarRequestInfo(strMsg));
        }
        private void websocket_Closed(object sender, EventArgs e)
        {
            //websocket.Send("一个客户端 下线");
        }
        void websocket_Opened(object sender, EventArgs e)
        {
            //websocket.Send("一个客户端 上线");
        }
        //向登录服务器发送数据
        public void Send<T>(T objMsg)
        {
            Send(Jsh.Jstr(objMsg));
        }

        //向登录服务器发送数据
        public void Send(string msg)
        {
            if (websocket == null)
            {
                LunarClientDebug.Error("请先连接到服务器！");
                return;
            }
            LinkState = (websocket.State == WebSocketState.Open);
            if (!LinkState)
            {
                LunarClientDebug.Error("请先连接到服务器！");
                return;
            }
            websocket.Send(msg);
        }
    }
}
